import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Paper } from './paper.schema';
import { responseBody } from 'src/utils/reponseUtils';

@Injectable()
export class PaperService {
  constructor(
    @InjectModel('Paper') private readonly paperModel: Model<Paper>,
  ) {}

  async getAllPapers(page = 1, pageSize = 10): Promise<PageResponse<Paper[]>> {
    const totalSize = await this.paperModel.countDocuments(); // Count total documents
    const papers = await this.paperModel
      .find()
      .select('-content')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .exec();
    return responseBody.okWithPageData<Paper[]>(papers, {
      totalSize,
      page,
      pageSize,
    });
  }

  async getPaperById(id: string): Promise<ResponseDate<Paper>> {
    const paper = await this.paperModel.findById(id).exec();
    return responseBody.okWithData(paper);
  }

  async createPaper(paper: Paper): Promise<ResponseDate<Paper>> {
    const htt = await import('html-to-text');
    const newPaper = new this.paperModel(paper);
    newPaper.createdTime = new Date();
    newPaper.desc = htt.htmlToText(paper.content.substring(0, 30));
    return responseBody.okWithData(await newPaper.save());
  }

  async updatePaper(id: string, paper: Paper): Promise<Paper> {
    return await this.paperModel.findByIdAndUpdate(id, paper, { new: true });
  }

  async deletePaper(id: string): Promise<any> {
    return await this.paperModel.findByIdAndDelete(id);
  }
}
